import React, { useState, useRef, useEffect, CSSProperties } from "react";
import type { FC } from "react";
import classNames from "classnames";
import styles from "./style.module.css";

export interface SwitchState {
  checked: boolean;
  disabled: boolean;
  openText: string | React.ReactNode;
  closeText: string | React.ReactNode;
  onChange: (state: boolean) => void;
  style: CSSProperties;
}

export const Switch: FC<Partial<SwitchState>> = ({
  checked,
  disabled,
  openText,
  closeText,
  onChange,
  style
}) => {
  const [state, setState] = useState(checked);
  const [switch_width, setSwitchWidth] = useState<number>(0);
  const switch_ref = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (switch_ref?.current) {
      setSwitchWidth(switch_ref.current?.offsetWidth);
    }
  }, []);

  useEffect(() => {
    setState(checked);
  }, [checked]);

  useEffect(() => {
    onChange?.(state as boolean);
  }, [state]);

  const switchClass = classNames("varan-switch", {
    "varan-switch-open": state && true,
    "varan-switch-close": !state && true,
    "varan-switch-disabled": disabled && true,
  })
    .split(" ")
    .map((i) => styles[i]);

  const handleSwitch = () => {
    !disabled && setState(!state);
  };
  return (
    <div
      ref={switch_ref}
      style={style}
      className={classNames(switchClass)}
      onClick={handleSwitch}>
      <span
        className={styles["varan-switch-text"]}
        style={state ? { left: 7 } : { left: switch_width - 30 }}>
        {state ? openText : closeText}
      </span>
      <div
        className={styles["varan-switch-radio"]}
        style={state ? { left: switch_width - 20 } : {}}></div>
    </div>
  );
};

Switch.defaultProps = {
  checked: false,
  disabled: false,
};
